/**
 * 
 */
package com.iwords.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.constants.Constants;
import com.iwords.service.LearningStatusServiceLocal;
import com.iwords.service.SysLibServiceLocal;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.WordServiceLocal;
import com.iwords.service.object.LearningStatusEntity;
import com.iwords.service.object.SysLibEntity;
import com.iwords.service.object.SysLibWordsEntity;
import com.iwords.service.object.WordNumber;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.HttpUtils;
import com.iwords.utils.StringUtils;
import com.iwords.web.base.BaseAction;

/**
 * @author       BOLIN.HBC 
 * @time         2011-4-5    
 * @description  用户学习状态-SERVLET       
 */
@WebServlet(name = "testAction", urlPatterns = {"/itis","/justAtest"})
public class TestAction extends BaseAction<LearningStatusEntity> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	private LearningStatusServiceLocal learningStatusService;
	@EJB
	private WordServiceLocal wordService;

	@EJB
	private UserServiceLocal userService;

	@EJB
	SysLibServiceLocal sysLibService;

	public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
		String action = req.getParameter("action");
		if (Constants.LEARNINGSTATUS_MOVE_SYSLIB.equals(action)) {

			doMoveSysLib(req, res);

		} else if (Constants.LEARNINGSTATUS_CHANGE_WORDSTATUS.equals(action)) {
			doChangeStatus(req, res);
		} else if (Constants.LEARNINGSTATUS_LIST.equals(action)) {
			doGetStatusList(req, res);
		} else if (Constants.LEARNINGSTATUS_STUDY.equals(action)) {
			doGetAllWordStatusByType(req, res);
		} else if (Constants.LEARNINGSTATUS_NEXT_WORD.equals(action)) {
			doGetNextLevelWord(req, res);
		}
	}

	public void doGetAllWordStatusByType(HttpServletRequest req, HttpServletResponse res) {

		SysLibWordsEntity currentWord = new SysLibWordsEntity();
		Long libId = null;
		if (req.getParameter("libId") == null || req.getParameter("libId").trim().length() == 0) {
			libId = userService.find(this.getUserId(req)).getCurrentlib();
		} else {
			libId = Long.parseLong(req.getParameter("libId"));

		}

		// 为了测试通过,暂时mock一下
		SysLibEntity currentLib = null;
		if (sysLibService == null) {
			currentLib = new SysLibEntity();
			currentLib.setLibid(348L);
			currentLib.setLibname("《牛津英语》(高一)(第二学期)");
			currentLib.setQuantity(329);

		} else {
			currentLib = sysLibService.findSysLibById(libId);
		}

		Map<String, WordNumber> map = getMyNumberMap(this.getUserId(req), libId);

		// wordid
		if (map.get("1").getCanReadList().size() > 0) {
			currentWord = map.get("1").getCanReadList().get(0);
		}
		initWord(currentWord);
		req.setAttribute("numberMap", map);
		req.setAttribute("currentLib", currentLib);
		req.setAttribute("currentWord", currentWord);
		req.setAttribute("currentLevel", "1");
		this.forward(req, res, Constants.WORD_JSP);
	}
	
	
	
	public Map<String, WordNumber> getMyNumberMap(Long userId,Long libId){
		Map<String, WordNumber> numberMap = new HashMap<String, WordNumber>();

		LearningStatusEntity status = new LearningStatusEntity();
		status.setUserid(userId);
		status.setLibid(libId);
		List<LearningStatusEntity> words = learningStatusService.getStatusList(status);
		numberMap.put("1", new WordNumber());
		numberMap.put("2", new WordNumber());
		numberMap.put("3", new WordNumber());
		numberMap.put("4", new WordNumber());
		numberMap.put("5", new WordNumber());
		numberMap.put("6", new WordNumber());
		numberMap.put("7", new WordNumber());
		if (words != null && words.size() > 0) {
			
			for (LearningStatusEntity entity : words) {

				switch (entity.getFamiliarity()) {
				case 0:
				case 1:
					init(entity, numberMap.get("1"));
					break;
				case 2:
					init(entity, numberMap.get("2"));
					break;
				case 3:
					init(entity, numberMap.get("3"));

					break;
				case 4:
					init(entity, numberMap.get("4"));

					break;
				case 5:
					init(entity, numberMap.get("5"));
					break;
				case 6:
					init(entity, numberMap.get("6"));
					break;
				case 7:
					init(entity, numberMap.get("7"));
					break;
				}
			}
		}
		return numberMap;
	}
	
	
	
	public void doGetNextLevelWord(HttpServletRequest req, HttpServletResponse res) throws IOException, JSONException {
		String currentLevel = req.getParameter("currentLevel");

		if (currentLevel == null) {
			currentLevel = "1";
		}
		String currentWordId = req.getParameter("currentWordId");

		// 0 表示上一个单词,1表示下一个单词
		String type = req.getParameter("type");
		if (type == null || type.isEmpty()) {
			type = "1";
		}

		
		SysLibWordsEntity cu = new SysLibWordsEntity();
		String libId = req.getParameter("libId");
		LearningStatusEntity status = new LearningStatusEntity();
		status.setUserid(this.getUserId(req));
		if (libId == null || libId.isEmpty()) {
			status.setLibid(userService.find(this.getUserId(req)).getCurrentlib());

		} else {
			status.setLibid(Long.parseLong(libId));
		}
		status.setFamiliarity(Integer.parseInt(currentLevel));

		Map<String, WordNumber> map = getMyNumberMap(this.getUserId(req), Long.parseLong(libId));

		List<SysLibWordsEntity> readList = map.get(currentLevel).getCanReadList();

		// 清理一次,将type==1的留下,其余的删除掉

		String error="";
		
		if (currentWordId == null || currentWordId.isEmpty()) {
			cu = readList.get(0);
		} else {

			for (int i = 0; i < readList.size(); i++) {

				if (readList.get(i).getWordid() == Long.parseLong(currentWordId)) {
					if (type.equals("0")) {

						if (i == 0) {
							cu = readList.get(readList.size() - 1);
							error=readList.get(i).getSpelling()+"的上一个是"+cu.getSpelling();
							break;

						} else {
							cu = readList.get(i - 1);
							error=readList.get(i).getSpelling()+"的上一个是"+cu.getSpelling();
							break;

						}
					} else {

						if (i == readList.size() - 1) {
							cu = readList.get(0);
							error=readList.get(i).getSpelling()+"的下一个是"+cu.getSpelling();
							break;
						} else {
							cu = readList.get(i + 1);
							error=readList.get(i).getSpelling()+"的下一个是"+cu.getSpelling();
							break;
						}

					}

				}

			}
		}
		initWord(cu);
		req.setAttribute("libId", libId);
		req.setAttribute("error", error);
		req.setAttribute("currentWord", cu);
		req.setAttribute("currentLevel", currentLevel);
		this.forward(req, res, Constants.CURRENT_WORD_JSP);

	}
	
	public void initWord(SysLibWordsEntity word) {
		String urlSens = HttpUtils.getResponse(Constants.DICT_CN_SEARCH_WORD + word.getSpelling().trim().toLowerCase());

		if (urlSens == null) {
			return;
		}
		String lines[] = urlSens.split("\n");
		for (int i = lines.length - 2; i >= 0; i--) {
			String line = lines[i];

			if (line.indexOf(Constants.DICT_CN_SEARCH_DEF) == -1 && line.indexOf(Constants.DICT_CN_SEARCH_DEF) == -1) {

				String s[] = line.split("<trans>");
				if (s.length == 2) {
					s[0] = s[0].replaceAll("<sent>", "").replaceAll("</orig>", "").replaceAll("<orig>", "").replaceAll("&lt;em", "<span class=\"b\"")
							.replaceAll("em&gt;", "span>").replaceAll("&gt;", ">").replaceAll("&lt;", "<");
					s[1] = s[1].replaceAll("<trans>", "").replaceAll("</trans>", "").replaceAll("</sent>", "").replaceAll("&lt;em", "<span class=\"b\"")
							.replaceAll("em&gt;", "span>").replaceAll("&gt;", ">").replaceAll("&lt;", "<");
					word.getSens().add(s[0] + "#" + s[1]);

				}
			}

		}

	}
 
	private void init(LearningStatusEntity entity, WordNumber num) {
		int type = this.getWordType(entity.getUpdatetime().getTime(), 0);
		if (type == 1) {
			num.setUp_number(num.getUp_number() + 1);
			num.getCanReadList().add(entity.getWord());
		} else {
			num.setDown_number(num.getDown_number() + 1);

		}
	}

	private int getWordType(long time, int day) {

		long t = System.currentTimeMillis() - time;

		if ((t + 0.0) / 60 * 60 * 24 >= day) {
			return 1;

		} else {

			return 2;
		}

	}
	
	
	
	public void doGetStatusList(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
		LearningStatusEntity entity = initEntity(req);
		JSONObject result = new JSONObject();
		result.put(Constants.IS_SUCCESS, Boolean.TRUE);
		try {
			List<LearningStatusEntity> resultList = learningStatusService.getStatusList(entity);

			List<SysLibWordsEntity> wordList = wordService.findWordsBySysLibId(entity.getLibid());
			Map<Long, SysLibWordsEntity> map = new HashMap<Long, SysLibWordsEntity>();
			for (SysLibWordsEntity en : wordList) {
				map.put(en.getWordid(), en);
			}

			JSONArray defaultValue = new JSONArray();

			for (LearningStatusEntity en : resultList) {
				JSONObject value = new JSONObject();
				SysLibWordsEntity e = map.get(en.getWord().getWordid());
				value.put("id", en.getId());
				value.put("libid", en.getLibid());
				value.put("wordid", en.getWord().getWordid());
				if (e != null) {
					value.put("spelling", CodeUtils.encode(e.getSpelling()));
					value.put("meaning",  CodeUtils.encode(e.getMeaning()));
					value.put("phonetics", CodeUtils.encode(e.getPhonetics()));
				}
				value.put("userid", en.getUserid());
				value.put("familiarity", en.getFamiliarity());

				defaultValue.put(value);
			}
			result.put(Constants.DEFAULT_VALUE, defaultValue);

		} catch (Exception e) {
			log.error("获取用户学习状态列表失败", e);
			result.put(Constants.IS_SUCCESS, Boolean.FALSE);
			result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
		}

	}

	public void doChangeStatus(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
		LearningStatusEntity entity = initEntity(req);
		// type=0 左移动 type=1 右移动

		if ("0".equals(req.getParameter("type"))) {
			if (entity.getFamiliarity() == 7) {
				return;
			} else {
				entity.setFamiliarity(entity.getFamiliarity() + 1);
			}
		} else {
			if (entity.getFamiliarity() == 1) {
				entity.setFamiliarity(7);
			} else {
				entity.setFamiliarity(entity.getFamiliarity() - 1);
			}

		}
		JSONObject result = new JSONObject();
		result.put(Constants.IS_SUCCESS, Boolean.TRUE);

		try {
			learningStatusService.changeStatus(entity);
		} catch (Exception e) {
			log.error("修改用户学习状态失败", e);
			result.put(Constants.IS_SUCCESS, Boolean.FALSE);
			result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
		}

	}

	public void doMoveSysLib(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
		LearningStatusEntity entity = initEntity(req);
		JSONObject result = new JSONObject();
		result.put(Constants.IS_SUCCESS, Boolean.TRUE);
		try {
			if (learningStatusService.moveSysLib(entity)) {
				result.put(Constants.DEFAULT_VALUE, true);
			}
		} catch (Exception e) {
			log.error("用户选择课本失败", e);
			result.put(Constants.IS_SUCCESS, Boolean.FALSE);
			result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
		}
	}

	public LearningStatusEntity initEntity(HttpServletRequest req) {
		LearningStatusEntity entity = new LearningStatusEntity();
		String userid = req.getParameter("userid");

		if (StringUtils.isNotBlank(userid)) {
			entity.setUserid(Long.parseLong(userid));
		} else {
			entity.setUserid(this.getUserId(req));
		}
		String wordid = req.getParameter("wordid");
		if (StringUtils.isNotBlank(wordid)) {
			SysLibWordsEntity word = new SysLibWordsEntity();
			word.setWordid(Long.parseLong(wordid));
			entity.setWord(word);
		}
		String libid = req.getParameter("libid");
		if (StringUtils.isNotBlank(libid)) {

			entity.setLibid(Long.parseLong(libid));
		}
		String familiarity = req.getParameter("familiarity");
		if (StringUtils.isNotBlank(familiarity)) {

			entity.setFamiliarity(Integer.parseInt(familiarity));
		} else {
			entity.setFamiliarity(0);

		}
		return entity;
	}

}
